<style scoped>
.empty-data {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  width: 100%;
  color: #666;
  font-size: 16px;
  border: 1px solid #eee;
}
</style>
<template>
  <div>
    <Row>
      <Col span="24">
        <Card class="margin-bottom-10">
          <Form inline>
            <FormItem class="margin-bottom-0">
              <Select
                v-model="searchConf.game_hash"
                filterable
                remote
                :remote-method="getGameName"
                style="width:260px"
                placeholder='请选择游戏'
                :loading="nameLoading"
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">
                  {{ option.label }}
                </Option>
              </Select>
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Input v-model="searchConf.keywords" placeholder="参数名称"/>
            </FormItem>
            <FormItem class="margin-bottom-0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Alert show-icon>
          修改配置后，并不代表立刻更新，请知悉！
          <Icon type="ios-bulb-outline" slot="icon"></Icon>
          <template slot="desc">系统将在每个整点检查是否更新配置，请注意新增、编辑、删除都将触发游戏配置更新！</template>
        </Alert>
        <Card>
          <div class="margin-bottom-15">
            <Button type="primary" v-has="'GameConfig/add'" @click="alertAdd" icon="md-add">{{ $t('add_button') }}
            </Button>
            <Button  class="margin-left-15" type="primary" v-has="'GameConfig/add'" @click="alertUpdate">同步配置
            </Button>
          </div>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover/>
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total/>
          </div>
        </Card>
      </Col>
    </Row>
    <Modal v-model="modalSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert"/>
        <span>{{ formItem.id ? '编辑' : '新增' }}配置</span>
      </p>
      <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
        <FormItem label="参数名称" prop="conf_key">
          <Input v-model="formItem.conf_key" placeholder="请输入参数名称"/>
        </FormItem>
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="所属游戏" prop="game_hash">
              <Select
                v-model="formItem.game_hash"
                filterable
                style="width:100%"
                placeholder='请选择游戏'
              >
                <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{ option.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="适用范围" prop="client_need">
              <Select
                v-model="formItem.client_need"
                filterable
                style="width:100%"
              >
                <Option :value="1" :key="1">客户端需要</Option>
                <Option :value="0" :key="0">客户端拒绝</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <FormItem label="参数描述" prop="desc">
          <Input type="textarea" v-model="formItem.desc" placeholder="请输入参数描述"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel" class="margin-right-10">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>

    <Modal v-model="modalNewSetting.show" width="668" :styles="{top: '30px'}" @on-visible-change="doUpdateCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert"/>
        <span>同步配置</span>
      </p>
      <Form ref="myUpdateForm" :rules="ruleValidate" :model="formUpdateItem" :label-width="80">
        <FormItem label="来源游戏" prop="game_hash_from">
          <Select
            v-model="formUpdateItem.game_hash_from"
            filterable
            style="width:100%"
            placeholder='请选择来源游戏'
          >
            <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{ option.label }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="目标游戏" prop="game_hash_to">
          <Select
            v-model="formUpdateItem.game_hash_to"
            filterable
            style="width:100%"
            placeholder='请选择目标游戏'
          >
            <Option v-for="(option, index) in gameNameOption" :value="option.value" :key="index">{{ option.label }}
            </Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="updateCancel" class="margin-right-10">取消</Button>
        <Button type="primary" @click="updateSubmit" :loading="modalNewSetting.loading">确定</Button>
      </div>
    </Modal>
    <Drawer
      title="配置详情"
      v-model="drawer.show"
      placement="bottom"
      height="80%"
      :mask-closable="false"
      :styles="drawer.styles"
    >
      <Upload
        v-if="drawer.columns.length === 0"
        :action="uploadUrl"
        :show-upload-list="false"
        :headers="uploadHeader"
        :format="['xls','xlsx']"
        :max-size="51200"
        :on-success="handleUpSuccess"
        :on-format-error="handleUpFormatError"
        :on-exceeded-size="handleUpMaxSize">
        <Button type="warning" class="margin-bottom-15"> 配置上传</Button>
      </Upload>
      <div v-else class="margin-bottom-15">
        <Button type="success" class="margin-right-10" @click="confirmConf"> 确认提交</Button>
        <Button type="primary" @click="resetConfirmData"> 重新上传</Button>
      </div>
      <ve-table
        v-if="drawer.columns.length"
        :columns="drawer.columns"
        :table-data="drawer.tableData"
      />
      <div v-else class="empty-data">暂无数据</div>
    </Drawer>
  </div>
</template>
<script>
import { add, confirmConf, del, edit, getList, updateConf } from '@/api/game-conf'
import config from '@/config'
import { getChoose } from '@/api/game-manager'
import { baseUrl } from '@/libs/api.request'
import { getToken } from '@/libs/util'

const editButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.edit) {
    return h('Button', {
      props: {
        type: 'primary'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.getGameName()
          vm.formItem.id = currentRow.id
          vm.formItem.conf_key = currentRow.conf_key
          vm.formItem.client_need = currentRow.client_need
          vm.formItem.game_hash = currentRow.game_hash
          vm.formItem.desc = currentRow.desc
          vm.modalSetting.show = true
          vm.modalSetting.index = index
        }
      }
    }, vm.$t('edit_button'))
  }
}
const deleteButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.del) {
    return h('Poptip', {
      props: {
        confirm: true,
        title: '您确定要删除这条数据吗? ',
        transfer: true
      },
      on: {
        'on-ok': () => {
          let paramsss = {
            id: currentRow.id,
            game_hash: currentRow.game_hash
          }
          del(paramsss).then(response => {
            vm.tableData.splice(index, 1)
            vm.$Message.success(response.data.msg)
          })
          currentRow.loading = false
        }
      }
    }, [
      h('Button', {
        style: {
          margin: '0 5px'
        },
        props: {
          type: 'error',
          placement: 'top',
          loading: currentRow.isDeleting
        }
      }, vm.$t('delete_button'))
    ])
  }
}
const detailButton = (vm, h, currentRow, index) => {
  if (vm.buttonShow.edit) {
    return h('Button', {
      props: {
        type: 'info'
      },
      style: {
        margin: '0 5px'
      },
      on: {
        'click': () => {
          vm.formConfItem.id = currentRow.id
          vm.formConfItem.game_hash = currentRow.game_hash
          vm.formConfItem.unique = ''
          vm.resetConfirmData()
          vm.drawer.show = true
        }
      }
    }, '配置导入')
  }
}

export default {
  name: 'game_config',
  data () {
    return {
      uploadUrl: baseUrl + 'GameConfig/importConf',
      uploadHeader: { 'Api-Auth': getToken(), Version: config.version, 'Connection-Code': 'center' },
      drawer: {
        show: false,
        styles: {
          height: 'calc(100% - 55px)',
          overflow: 'auto',
          paddingBottom: '53px',
          position: 'static'
        },
        tableData: [],
        columns: []
      },
      typeList: [],
      originType: {},
      nameLoading: false,
      gameNameOption: [],
      gameShow: {},
      columnsList: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center'
        },
        {
          title: '参数名称',
          align: 'center',
          key: 'conf_key',
          width: 260
        },
        {
          title: '参数描述',
          align: 'center',
          key: 'desc',
          minWidth: 300
        },
        {
          title: '配置详情',
          align: 'center',
          width: 150,
          render: (h, params) => {
            if (params.row.unique) {
              return h('Button', {
                props: {
                  type: 'primary',
                  target: '_blank',
                  to: 'https://commoncdn.qingmanet.com/sldnf/game_config_json/' + params.row.unique + '.json'
                },
                style: {
                  margin: '0 5px'
                }
              }, '配置查看')
            } else {
              return h('Tag', {
                attrs: {
                  color: 'warning'
                }
              }, '暂未上传')
            }
          }
        },
        {
          title: '所属游戏',
          align: 'center',
          render: (h, params) => {
            this.getGameName()
            return h('span', this.gameShow[params.row.game_hash])
          },
          width: 220
        },
        {
          title: '最近更新',
          align: 'center',
          key: 'updated_at',
          width: 170
        },
        {
          title: '操作',
          align: 'center',
          width: 280,
          render: (h, params) => {
            return h('div', [
              detailButton(this, h, params.row, params.index),
              editButton(this, h, params.row, params.index),
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      tableData: [],
      groupList: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        game_hash: '',
        keywords: ''
      },
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      modalNewSetting: {
        show: false,
        loading: false,
        index: 0
      },
      delParams: {
        game_hash: '',
        id: 0
      },
      formItem: {
        conf_key: '',
        game_hash: '',
        client_need: 1,
        desc: '',
        id: 0
      },
      formConfItem: {
        id: 0,
        game_hash: '',
        unique: ''
      },
      formUpdateItem: {
        game_hash_from: '',
        game_hash_to: ''
      },
      ruleValidate: {
        conf_key: [
          { required: true, message: '参数名称不能为空', trigger: 'blur' }
        ],
        game_hash: [
          { required: true, message: '请选择游戏', trigger: 'blur' }
        ]
      },
      buttonShow: {
        edit: true,
        del: true
      },
      listLoading: false
    }
  },
  created () {
    let vm = this
    vm.getList()
    vm.hasRule('GameConfig/edit').then(res => {
      vm.buttonShow.edit = res
    })
    vm.hasRule('GameConfig/del').then(res => {
      vm.buttonShow.del = res
    })
  },
  methods: {
    handleUpFormatError (file) {
      this.$Notice.warning({
        title: '文件类型不合法',
        desc: file.name + '的文件类型不正确，请上传jpg或者png图片。'
      })
    },
    handleUpSuccess (response) {
      if (response.code === 1) {
        this.drawer.columns = []
        this.drawer.tableData = response.data.data.slice(0, 20)
        for (let i = 0; i < response.data.header.length; i++) {
          this.drawer.columns.push({
            field: response.data.header[i],
            key: response.data.header[i],
            title: response.data.header[i]
          })
        }
        this.formConfItem.unique = response.data.unique

        this.$Message.success(response.msg)
      } else {
        this.$Message.error(response.msg)
      }
    },
    handleUpMaxSize (file) {
      this.$Notice.warning({
        title: '文件大小不合法',
        desc: file.name + '太大啦请上传小于5M的文件。'
      })
    },
    alertAdd () {
      this.getGameName()
      this.modalSetting.show = true
    },
    alertUpdate () {
      this.getGameName()
      this.modalNewSetting.show = true
    },
    getGameName (value) {
      if (!this.gameNameOption.length) {
        getChoose({
          keyword: value
        }).then(response => {
          this.gameNameOption = response.data.data.list
          this.gameNameOption.forEach(i => {
            this.gameShow[i.value] = i.label
          })
        })
      }
    },
    submit () {
      let vm = this
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          vm.modalSetting.loading = true
          if (vm.formItem.id === 0) {
            add(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          } else {
            edit(vm.formItem).then(response => {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            }).catch(() => {
              vm.modalSetting.loading = false
            })
          }
        }
      })
    },
    updateSubmit () {
      let vm = this
      this.$refs['myUpdateForm'].validate((valid) => {
        if (valid) {
          vm.modalNewSetting.loading = true
          updateConf(vm.formUpdateItem).then(response => {
            vm.$Message.success(response.data.msg)
            vm.getList()
            vm.updateCancel()
          }).catch(() => {
            vm.modalNewSetting.loading = false
          })
        }
      })
    },
    confirmConf () {
      let vm = this
      confirmConf(vm.formConfItem).then(response => {
        vm.$Message.success(response.data.msg)
        vm.resetConfirmData()
        vm.getList()
        vm.drawer.show = false
      }).catch(() => {
        vm.modalSetting.loading = false
      })
    },
    resetConfirmData () {
      this.drawer.columns = []
      this.drawer.tableData = []
    },
    cancel () {
      this.modalSetting.show = false
    },
    updateCancel () {
      this.modalNewSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.formItem.type = []
        this.$refs['myForm'].resetFields()
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    doUpdateCancel (data) {
      if (!data) {
        this.$refs['myUpdateForm'].resetFields()
        this.modalNewSetting.loading = false
        this.modalNewSetting.index = 0
      }
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        ...vm.searchConf
      }
      vm.listLoading = true
      getList(params).then(response => {
        vm.tableData = response.data.data.list
        vm.tableShow.listCount = response.data.data.count
        vm.listLoading = false
      })
    }
  }
}
</script>
